
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文章阅读 - 我的博客</title>
    <!-- 引入Vditor的样式，仅用于渲染Markdown -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vditor@3.9.6/dist/index.css" />
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f7f7f7;
            color: #333;
            line-height: 1.6;
        }
        .header {
            background-color: #ffffff;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            padding: 15px 0;
            position: sticky;
            top: 0;
            z-index: 1000;
        }
        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 20px;
        }
        .header h1 {
            margin: 0;
            font-size: 1.5rem;
            color: #333;
        }
        .action-buttons a {
            margin-left: 15px;
            text-decoration: none;
            padding: 8px 16px;
            border-radius: 4px;
            font-weight: 500;
            font-size: 14px;
            transition: all 0.2s;
        }
        .edit-btn {
            background-color: #4285f4;
            color: white !important;
        }
        .edit-btn:hover {
            background-color: #3367d6;
        }
        .home-btn {
            background-color: #f1f3f4;
            color: #333 !important;
        }
        .home-btn:hover {
            background-color: #dfe1e5;
        }
        .container {
            max-width: 1200px;
            margin: 20px auto;
            display: flex;
            gap: 20px;
        }
        .content-container {
            flex: 1;
            background-color: #fff;
            padding: 30px;
            border-radius: 5px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .article-header {
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        .article-title {
            margin: 0 0 10px 0;
            font-size: 2rem;
            color: #222;
        }
        .article-meta {
            color: #666;
            font-size: 14px;
        }
        .toc-container {
            width: 250px;
            background-color: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            position: sticky;
            top: 85px;
            max-height: calc(100vh - 120px);
            overflow-y: auto;
        }
        .toc-title {
            font-weight: bold;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
            color: #333;
        }
        #toc-content ul {
            padding-left: 20px;
            margin: 8px 0;
        }
        #toc-content li {
            margin: 5px 0;
            list-style-type: none;
        }
        #toc-content a {
            color: #555;
            text-decoration: none;
            display: block;
            padding: 5px 0;
            font-size: 14px;
            border-left: 2px solid transparent;
            padding-left: 10px;
            transition: all 0.2s;
        }
        #toc-content a:hover {
            color: #4285f4;
            border-left-color: #4285f4;
            background-color: rgba(66, 133, 244, 0.05);
        }
        #toc-content a.active {
            color: #4285f4;
            border-left-color: #4285f4;
            font-weight: 500;
        }
        #article-content {
            line-height: 1.8;
            font-size: 16px;
        }
        #article-content h1, 
        #article-content h2, 
        #article-content h3, 
        #article-content h4, 
        #article-content h5, 
        #article-content h6 {
            margin-top: 1.5em;
            margin-bottom: 0.5em;
        }
        #article-content h1 {
            font-size: 1.8em;
            padding-bottom: 0.3em;
            border-bottom: 1px solid #eaecef;
        }
        #article-content h2 {
            font-size: 1.5em;
            padding-bottom: 0.3em;
            border-bottom: 1px solid #eaecef;
        }
        #article-content h3 {
            font-size: 1.25em;
        }
        #article-content p {
            margin-bottom: 16px;
        }
        #article-content pre {
            padding: 16px;
            overflow: auto;
            font-size: 85%;
            line-height: 1.45;
            background-color: #f6f8fa;
            border-radius: 3px;
        }
        #article-content code {
            font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace;
        }
        #article-content table {
            border-collapse: collapse;
            width: 100%;
            margin-bottom: 16px;
        }
        #article-content table th,
        #article-content table td {
            padding: 8px;
            border: 1px solid #dfe2e5;
        }
        #article-content table th {
            background-color: #f6f8fa;
        }
        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                flex-direction: column;
            }
            .toc-container {
                width: auto;
                position: static;
                max-height: none;
                margin-bottom: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-content">
            <h1>我的博客</h1>
            <div class="action-buttons">
                <a href="/" class="home-btn">首页</a>
                <a href="#" id="edit-link" class="edit-btn">编辑文章</a>
            </div>
        </div>
    </div>

    <div class="container">
        <div class="content-container">
            <div class="article-header">
                <h1 class="article-title" id="article-title">加载中...</h1>
                <div class="article-meta" id="article-meta">
                    最后更新: <span id="update-time">加载中...</span>
                </div>
            </div>
            <div id="article-content"></div>
        </div>

        <div class="toc-container">
            <div class="toc-title">目录</div>
            <div id="toc-content"></div>
        </div>
    </div>

    <!-- 引入Vditor的脚本 -->
    <script src="https://cdn.jsdelivr.net/npm/vditor@3.9.6/dist/index.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const articleContent = document.getElementById('article-content');
            const articleTitle = document.getElementById('article-title');
            const updateTime = document.getElementById('update-time');
            const tocContent = document.getElementById('toc-content');
            const editLink = document.getElementById('edit-link');

            // 从URL获取文件名
            let filename = '{{ filename }}';
            if (!filename) {
                filename = 'kk.md';
            }

            // 设置编辑链接
            editLink.href = `/edit/${filename}`;

            // 加载文章内容
            loadArticle(filename);

            // Markdown预览器元素
            let previewElement;

            // 加载文章内容
            function loadArticle(filename) {
                articleTitle.textContent = '加载中...';
                updateTime.textContent = '加载中...';

                fetch(`/api/get_markdown?filename=${encodeURIComponent(filename)}`)
                    .then(response => {
                        if (!response.ok) {
                            return response.json().then(data => {
                                throw new Error(data.error || `无法加载文件，状态码: ${response.status}`);
                            });
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data.content) {
                            // 设置文章标题（使用第一个#标题）
                            const titleMatch = data.content.match(/^# (.*?)$/m);
                            if (titleMatch && titleMatch[1]) {
                                articleTitle.textContent = titleMatch[1];
                                document.title = titleMatch[1] + " - 我的博客";
                            } else {
                                articleTitle.textContent = filename.replace('.md', '');
                                document.title = filename.replace('.md', '') + " - 我的博客";
                            }

                            // 设置更新时间
                            updateTime.textContent = data.modified || new Date().toLocaleString();

                            // 渲染Markdown内容
                            renderMarkdown(data.content);

                            // 生成目录
                            generateTOC(data.content);
                        } else {
                            articleTitle.textContent = '加载失败';
                            articleContent.innerHTML = '<p>无法加载文章内容</p>';
                            tocContent.innerHTML = '';
                        }
                    })
                    .catch(error => {
                        articleTitle.textContent = '出错了';
                        articleContent.innerHTML = `<p>错误: ${error.message}</p>`;
                        tocContent.innerHTML = '';
                        console.error('Error:', error);
                    });
            }

            // 渲染Markdown内容
            function renderMarkdown(markdown) {
                if (previewElement) {
                    // 如果已存在预览器，直接更新内容
                    Vditor.preview(previewElement, markdown, {
                        hljs: {
                            enable: true,
                            style: 'github',
                            lineNumber: true
                        },
                        after: () => {
                            // 给所有标题添加id
                            addHeadingIds();
                            // 设置目录项的活动状态监听
                            setupScrollSpy();
                        }
                    });
                } else {
                    // 首次创建预览器
                    previewElement = document.createElement('div');
                    articleContent.appendChild(previewElement);

                    Vditor.preview(previewElement, markdown, {
                        hljs: {
                            enable: true,
                            style: 'github',
                            lineNumber: true
                        },
                        after: () => {
                            // 给所有标题添加id
                            addHeadingIds();
                            // 设置目录项的活动状态监听
                            setupScrollSpy();
                        }
                    });
                }
            }

            // 给所有标题添加id
            function addHeadingIds() {
                const headings = document.querySelectorAll('#article-content h1, #article-content h2, #article-content h3, #article-content h4, #article-content h5, #article-content h6');
                headings.forEach(heading => {
                    if (!heading.id) {
                        heading.id = heading.textContent.toLowerCase().replace(/\s+/g, '-');
                    }
                });
            }

            // 生成目录
            function generateTOC(markdown) {
                const headingPattern = /^(#+)\s+(.+)$/gm;
                const headings = [];
                let match;

                while ((match = headingPattern.exec(markdown)) !== null) {
                    const level = match[1].length;
                    const text = match[2].trim();
                    const id = text.toLowerCase().replace(/\s+/g, '-');
                    headings.push({ level, text, id });
                }

                // 构建目录HTML
                let tocHtml = '<ul>';
                let prevLevel = 0;

                headings.forEach((heading, index) => {
                    const { level, text, id } = heading;

                    // 处理缩进和嵌套
                    if (level > prevLevel) {
                        for (let i = 0; i < level - prevLevel; i++) {
                            tocHtml += '<ul>';
                        }
                    } else if (level < prevLevel) {
                        for (let i = 0; i < prevLevel - level; i++) {
                            tocHtml += '</ul>';
                        }
                    }

                    tocHtml += `<li><a href="#${id}" data-heading-id="${id}">${text}</a></li>`;
                    prevLevel = level;
                });

                // 关闭所有打开的ul标签
                for (let i = 0; i < prevLevel; i++) {
                    tocHtml += '</ul>';
                }

                tocHtml += '</ul>';
                tocContent.innerHTML = tocHtml;

                // 设置目录项点击事件
                document.querySelectorAll('#toc-content a').forEach(link => {
                    link.addEventListener('click', function(e) {
                        e.preventDefault();
                        const id = this.getAttribute('data-heading-id');
                        const target = document.getElementById(id);
                        if (target) {
                            target.scrollIntoView({ behavior: 'smooth' });
                        }
                    });
                });
            }

            // 设置滚动监听，高亮当前目录项
            function setupScrollSpy() {
                const headings = Array.from(document.querySelectorAll('#article-content h1, #article-content h2, #article-content h3, #article-content h4, #article-content h5, #article-content h6'));
                if (headings.length === 0) return;

                const tocLinks = document.querySelectorAll('#toc-content a');

                window.addEventListener('scroll', () => {
                    // 获取当前可视区域
                    const scrollPos = window.scrollY + 100;

                    // 找到当前可视区域中的标题
                    let currentHeading = headings[0];
                    for (const heading of headings) {
                        if (heading.offsetTop <= scrollPos) {
                            currentHeading = heading;
                        } else {
                            break;
                        }
                    }

                    // 高亮对应的目录项
                    tocLinks.forEach(link => {
                        link.classList.remove('active');
                        if (link.getAttribute('data-heading-id') === currentHeading.id) {
                            link.classList.add('active');
                        }
                    });
                });
            }
        });
    </script>
</body>
</html>
